;
; Startup code for cc65 (C64 16k CRT)
; No IRQ support at the moment
;

		.export         _exit
		.export         __STARTUP__ : absolute = 1      ; Mark as startup

		.import _main
		.import decrunch
		.import _setup_cruncher
		.import initlib, donelib, copydata, callirq
		.import zerobss
		.import	       	__INTERRUPTOR_COUNT__
		.import __RAM_START__, __RAM_SIZE__     ; Linker generated
		.import __DATA_SIZE__, __DATA_LOAD__, __DATA_RUN__
		.import __EAPI_START__, __EAPIRAM_START__

		.include "zeropage.inc"
		.include "c64.inc"


; ------------------------------------------------------------------------
; Place the startup code in a special segment.

.segment           "STARTUP"


CINT   = $ff81
IOINIT = $ff84
RAMTAS = $ff87
RESTOR = $ff8a

		.addr	cold_start
		.addr	warm_start
		.byte   "CBM80"

cold_start:		
		ldx #0
		stx $d016
		jsr IOINIT
		jsr RAMTAS
		jsr RESTOR
		jsr CINT

		cli

		jsr zerobss
		
warm_start:
		; Switch to second charset
		;lda #14
		;jsr $FFD2

		jsr copydata
		
		; and here
		; Set argument stack ptr
		lda #<(__RAM_START__ + __RAM_SIZE__)
		sta sp
		lda #>(__RAM_START__ + __RAM_SIZE__)
		sta sp + 1

		; If we have IRQ functions, chain our stub into the IRQ vector

        lda     #<__INTERRUPTOR_COUNT__
      	beq	NoIRQ1
      	lda	IRQVec
       	ldx	IRQVec+1
      	sta	IRQInd+1
      	stx	IRQInd+2
      	lda	#<IRQStub
      	ldx	#>IRQStub
      	sei
      	sta	IRQVec
      	stx	IRQVec+1
      	cli

NoIRQ1:	jsr initlib

		lda #$01
		sta $d020
		sta $d021

		jsr _main

_exit:
		jsr donelib
exit:
		jmp exit


		
; ------------------------------------------------------------------------
; The IRQ vector jumps here, if condes routines are defined with type 2.

IRQStub:
	cld    	       		   	; Just to be sure
       	jsr    	callirq                 ; Call the functions
       	jmp    	IRQInd			; Jump to the saved IRQ vector

; ------------------------------------------------------------------------
; Data

.data

IRQInd: jmp     $0000

.segment        "ZPSAVE"

zpsave:	.res	zpspace

.bss

spsave:	.res	1
mmusave:.res	1